//
//  PlantViewController.m
//  SXH
//
//  Created by 龚啸 on 15/11/11.
//  Copyright © 2015年 lyss. All rights reserved.
//

#import "PlantViewController.h"
#import "CommonService.h"
#import "LocationManagement.h"
#import "OpenUDID.h"

#import "UIImageView+WebCache.h"
#import "PlantEntity.h"
#import "WebViewController.h"
#import "PlantCollectionViewCell.h"
#import "MJRefresh.h"
#import "AnimalAndPlantView.h"

#define PLANTBASE        @"/knowledge/query"

static const int kdistance = 7;
static const int kedge = 17;
static NSString * CellIdentifier = @"PlantCollectionViewCell";

@interface PlantViewController ()<AnimalViewDelegate> {
    NSMutableArray * arrayPlant;
    CGFloat cHeight;
    CGFloat cWidth;
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page1;
    float lastOffset;
    BOOL isAnimation;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstant;
@property (weak, nonatomic) IBOutlet UICollectionView *plantCollectionView;
@property (copy, nonatomic) NSString * class_id;
@property (assign, nonatomic) NSInteger selectIndex;
@end

@implementation PlantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    lastOffset = 0;
    isAnimation = NO;
    [_plantCollectionView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
    _plantCollectionView.backgroundColor = [UIColor whiteColor];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    //横向
    [flowLayout setMinimumInteritemSpacing:7.0f];
    //AllLine
    [flowLayout setMinimumLineSpacing:0.0f];
    self.selectIndex = 1;
    
    [_plantCollectionView setCollectionViewLayout:flowLayout];
    [_plantCollectionView setBackgroundColor:[UIColor colorWithRed:0.937 green:0.941 blue:0.945 alpha:1.00]];
    arrayPlant = [[NSMutableArray alloc] init];
    cHeight = (SCREEN_WIDTH-kdistance*3-kedge*2)*109/80/4;
    cWidth = (SCREEN_WIDTH-kdistance*3-kedge*2)/4;
    if (_animal_knowledge) {
        AnimalAndPlantView * headView = [[AnimalAndPlantView alloc ] initWithFrame:CGRectMake(0, 64, ScreenWidth, 43)];
        headView.delegate = self;
        [self.view addSubview:headView];
        _topConstant.constant = 43;
           }
    
    [self addHeader];
    [self addFooter];
    // Do any additional setup after loading the view from its nib.
}

-(void)setSelectIndex:(NSInteger)selectIndex {
    _selectIndex = selectIndex;
    self.class_id =[NSString stringWithFormat:@"%ld",(long)selectIndex];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)getPlantData:(int)pageNo RefreshView:(MJRefreshBaseView *)refreshView
{
    CommonService *service = [[CommonService alloc] init];

    NSString * page =[NSString stringWithFormat:@"%d",pageNo];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:self.parkId, @"park_id",
                                                                    self.class_id,@"class_id",
                                                                        page,@"page",
                                                                       @"48",@"limit",nil];
    
    [service getNetWorkData:param
                       Path:PLANTBASE
                  Successed:^(id entity) {
                      if (pageNo == 1) {
                            [arrayPlant removeAllObjects];
                      }
                    
                      NSMutableArray *rows = [(NSDictionary *)entity valueForKey:@"rows"];
                      
                      for (int i = 0; i<[rows count]; i++) {
                          PlantEntity * entity = [[PlantEntity alloc] initWithAttributes:rows[i]];
                          [arrayPlant addObject:entity];
                           }
                     
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [self doneWithView:refreshView];
                      });
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [self doneWithView:refreshView];
                      });
                      DebugLog(@"%@", message);
                  }];

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [arrayPlant count];
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (isAnimation) {
        cell.transform = CGAffineTransformMakeTranslation(0, 60);
        [UIView animateWithDuration:1 animations:^{
            cell.transform = CGAffineTransformIdentity ;
        }];
        
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
    PlantCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    PlantEntity * entity = [arrayPlant objectAtIndex:indexPath.row];
    [cell.imageViewPlant sd_setImageWithURL:[NSURL URLWithString:entity.album_thumb]];
    cell.labelTitle.text = entity.title;
//    cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(cWidth, cHeight);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
//    if (section%4 == 1 ) {
//        return UIEdgeInsetsMake(kdistance, kedge , 0, kdistance/2);
//    }else if(section%4 == 0){
//        return UIEdgeInsetsMake(kdistance, kedge , 0, kdistance/2);
//    }
//    else{
        return UIEdgeInsetsMake(kdistance+8, kedge , 0, kedge);
//    }
  
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PlantEntity * entity = [arrayPlant objectAtIndex:indexPath.row];
//    NSString *url = [NSString stringWithFormat:@"http://web.leyouss.com/park/plant/%@/%@?ignore=0&locale=zh_cn&custom=0",self.parkId,entity.ID];
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = entity.url;
    vc.vcTitle = entity.title;
    vc.contentShare =entity.title;
    [[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:entity.album_thumb] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        vc.imageShare = image;}];

    [self.navigationController pushViewController:vc animated:YES];
    
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    isAnimation = scrollView.contentOffset.y >= lastOffset;
    lastOffset = scrollView.contentOffset.y;
    
}


-(void)animalViewSelectedIndex:(NSInteger)selectedIndex
{
    page1 = 1;
    if (selectedIndex ==1) {
        self.selectIndex = 2;
        [_plantCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        [self getPlantData:page1 RefreshView:nil];
        DebugLog(@"111111111111");
    }else{
        self.selectIndex = 1;
         [_plantCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        [self getPlantData:page1 RefreshView:nil];
        DebugLog(@"0000000000");
    }
}
- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
//    [arrayPlant removeAllObjects];
    
}
- (void)addHeader
{
    __unsafe_unretained __typeof(self) weakSelf = self;
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = weakSelf.plantCollectionView;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        page1 =1;
        [self getPlantData:1 RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}
- (void)addFooter
{
    __unsafe_unretained __typeof(self) weakSelf = self;
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = weakSelf.plantCollectionView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page1;
        [self getPlantData:page1 RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    if (refreshView) {
        [refreshView endRefreshing];
    }
    [self.plantCollectionView reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    
}
@end
